import { textToSpeech } from '@kit.CoreSpeechKit';
import { BusinessError } from '@kit.BasicServicesKit';

class ttsCtrl {
  private _id = 0;
  private ttsEngine: textToSpeech.TextToSpeechEngine = null!;
  extraParam: Record<string, Object> = {
    "speed": 1.25,
    "volume": 1,
    "pitch": 0.9,
    "languageContext": 'zh-CN',
    "audioType": "pcm",
    "playType": 1
  };

  init() {
    if (this.ttsEngine) {
      return;
    }
    // 创建引擎实例相关参数
    let extraParam: Record<string, Object> = { "style": 'interaction-broadcast', "locate": 'CN', "name": 'EngineName' };
    let initParamsInfo: textToSpeech.CreateEngineParams = {
      language: 'zh-CN',
      person: 0,
      online: 1,
      extraParams: extraParam
    };

    // 调用createEngine方法
    textToSpeech.createEngine(initParamsInfo).then((res: textToSpeech.TextToSpeechEngine) => {
      // 获得引擎实例
      this.ttsEngine = res;
      console.info('result succeeded:' + res);
      let speakListener: textToSpeech.SpeakListener = {
        // 开始合成或播报回调
        onStart(requestId: string, response: textToSpeech.StartResponse) {
          console.info('onStart: ' + 'requestId: ' + requestId);
        },
        // 合成完成或播报完成回调
        onComplete(requestId: string, response: textToSpeech.CompleteResponse) {
          console.info('onComplete: ' + 'requestId: ' + requestId);
        },
        // 停止合成或播报回调
        onStop(requestId: string, response: textToSpeech.StopResponse) {
          console.info('onStop: ' + 'requestId: ' + requestId);
        },
        // 返回音频流
        onData(requestId: string, audio: ArrayBuffer, response: textToSpeech.SynthesisResponse) {
          console.log('speakListener onData: ' + ' requestId: ' + requestId + ' audio: ' + audio);
        },
        // 错误回调
        onError(requestId: string, errorCode: number, errorMessage: string) {
          console.error('OnError: ' + 'requestId: ' + requestId + ' errorCode: ' + errorCode + 'errorMessage: ' +
            errorMessage);
        }
      };
      // 设置回调
      this.ttsEngine.setListener(speakListener);
    }).catch((err: BusinessError) => {
      console.error('err' + err.code);
      console.error('err' + err.message);
    });

  }

  speak(text: string) {
    this._id++;
    let speakParams: textToSpeech.SpeakParams = {
      requestId: this._id + "", // requestId在同一实例内仅能用一次，请勿重复设置
      extraParams: this.extraParam
    }
    this.ttsEngine.speak(text, speakParams);
  }

  stop() {
    this.ttsEngine.stop()
  }
}

let tts = new ttsCtrl();

export default tts;